import type { ErrorInfo } from 'react';
import React from 'react';
import { Button, Result } from 'antd';

class ErrorBoundary extends React.Component<
  Record<string, any>,
  { hasError: boolean; errorInfo: string }
> {
  state = { hasError: false, errorInfo: '' };

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, errorInfo: error.message };
  }

  UNSAFE_componentWillMount() {
    window.addEventListener(
      'error',
      (event: any) => {
        if (event.reason) {
          // const err = event.reason.toString();
          // console.log(err);
        }
      },
      true,
    );
    window.addEventListener('unhandledrejection', (event: any) => {
      if (event.reason) {
        // const err = event.reason.toString();
        // console.log(err);
      }
    });
  }

  componentDidCatch(error: any, errorInfo: ErrorInfo) {
    // You can also log the error to an error reporting service
    // eslint-disable-next-line no-console
    console.log(error, errorInfo);
  }

  render() {
    const { hasError, errorInfo } = this.state;
    if (hasError) {
      // You can render any custom fallback UI
      return (
        <Result
          icon={<img width={256} style={{ marginRight: '-100px' }} src="/error.png" />}
          style={{
            height: '100vh',
            background: '#fff',
          }}
          title=""
          extra={
            <>
              <div
                style={{
                  maxWidth: 620,
                  textAlign: 'start',
                  backgroundColor: 'rgba(255,229,100,0.3)',
                  borderInlineStartColor: '#ffe564',
                  borderInlineStartWidth: '9px',
                  borderInlineStartStyle: 'solid',
                  padding: '20px 45px 20px 26px',
                  margin: 'auto',
                  marginBlockEnd: '30px',
                  marginBlockStart: '20px',
                }}
              >
                <p>渲染错误:</p>
                <p>可能以下场景中产生的错误：</p>
                <ul
                  style={{
                    listStyle: 'none',
                  }}
                >
                  <li>1.程序已经更新最新版本</li>
                  <li>2.网络错误</li>
                  <li>3.服务端渲染</li>
                  <li>4.这是有个BUG</li>
                </ul>
                <p>{errorInfo}</p>
              </div>
              <Button
                danger
                type="primary"
                onClick={() => {
                  window.location.reload();
                }}
              >
                刷新页面
              </Button>
            </>
          }
        />
      );
    }
    return this.props.children;
  }
}
export default ErrorBoundary;
